import { QueryClient, useQuery } from 'react-query';
import { dehydrate } from 'react-query/hydration';
import { useRouter } from "next/router";
import CourseLayout from "@/components/course-layout";
import QuestionList from "@/components/question-list";
import { getCourseById } from "@/apis/course";
import { getQuestionsByExerciseId } from "@/apis/exercise";
import { display } from '@/tools/debug-tools';
import { isCourseManager } from '@/tools/data-helpers';


export default function QuestionListPage() {

    const { courseId, exerciseId } = useRouter().query;

    const { data: course } = useQuery(['course', courseId], ({ queryKey }) => {
        const [_key, courseId] = queryKey;
        return getCourseById(courseId)
    });

    const { data: questions } = useQuery(['questions', exerciseId], ({ queryKey }) => {
        const [_key, exerciseId] = queryKey;
        return getQuestionsByExerciseId(exerciseId);
    });


    return (
        <CourseLayout course={course} courseId={courseId}>
            <QuestionList questions={questions} exerciseId={exerciseId} isCourseManager={isCourseManager(course && course.manager)} courseId={courseId} />
        </CourseLayout>
    )
};

export async function getServerSideProps({ query }) {
    const queryClient = new QueryClient()

    await queryClient.prefetchQuery(['course', query.courseId], ({ queryKey }) => {
        const [_key, courseId] = queryKey;
        return getCourseById(courseId);
    });
    await queryClient.prefetchQuery(['questions', query.exerciseId], ({ queryKey }) => {
        const [_key, exerciseId] = queryKey;
        return getQuestionsByExercisesId(exerciseId);
    });

    return {
        props: {
            dehydratedState: dehydrate(queryClient),
        },
    }
}
